"""Setup the pacp application"""
import logging

from pacp.config.environment import load_environment
from pacp.model import meta, Run, Details
from pacp.lib.pipetech import PipeTech, FLDS

log = logging.getLogger(__name__)

def setup_app(command, conf, vars):
    """Place any commands to setup pacp here"""
    load_environment(conf.global_conf, conf.local_conf)

    # Create the tables if they don't already exist
    meta.metadata.create_all(bind=meta.engine)
    
    #import runs table
    tbl = 'Runs'
    env = r'C:\env\pacp\DLZ MK PACP.mdb'
    password = 'sigchi'
    pt = PipeTech(env, password)
    run_flds = FLDS['Runs']
    log.info("Adding Runs record")
    for inspection in pt.query('Runs', 1):
        run = Run()
        for fld in run_flds:
            idx = run_flds.index(fld)
            setattr(run, fld, inspection[idx])
        meta.Session.add(run)
    meta.Session.commit()
    log.info("Populating Runs Field Finished")
    details_flds = FLDS['Details']
    log.info("Start populating Details")
    for detail in pt.query('Details', 1):
        r = Details()
        for fld in details_flds:
            idx = details_flds.index(fld)
            setattr(r, fld, detail[idx])
            meta.Session.add(r)
    meta.Session.commit()
    log.info("Populating Details Finished")
    
    
        

